Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

some proxies may add port number to X-Forwarded-For header. #533

Merged
merged 1 commit into from
Jan 16, 2024

Conversation

shogo82148
Copy link
Owner

@shogo82148 shogo82148 commented Jan 16, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced IP address detection for clients behind proxies.
  • Bug Fixes

    • Improved handling of IPv6 addresses and port numbers in HTTP headers.
  • Tests

    • Added tests for various scenarios involving client IP address recognition.

Copy link

coderabbitai bot commented Jan 16, 2024

Walkthrough

The recent update enhances the HTTP handler's ability to accurately determine a client's IP address. It now interprets the Forwarded and X-Forwarded-For HTTP headers, with new logic to handle potential port numbers. Additionally, a getHost function has been introduced, designed to extract the host and port details from a given string. The test suite has been expanded to ensure the updated clientIP function correctly processes various IP address scenarios.

Changes

Files Change Summary
xrayhttp/handler.go Updated clientIP function; Added getHost function
xrayhttp/handler_test.go Enhanced TestClientIP to cover IPv6, multiple IPs, and IP with ports

Poem

🐇💻🌐

In the web's vast burrow, a clever update hops,
Parsing headers with ease, through the data it bobs.
Ports and IPs, entwined in a digital dance,
CodeRabbit rejoices, as the tests advance.
🎉🐾

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 2f1505d and 848892a.
Files selected for processing (2)
  • xrayhttp/handler.go (1 hunks)
  • xrayhttp/handler_test.go (1 hunks)
Additional comments: 2
xrayhttp/handler.go (1)
  • 196-203: The getHost function correctly splits the host and port from a given string and returns just the host part if the split is successful. This is a useful utility function for handling IP addresses that may include port numbers.
xrayhttp/handler_test.go (1)
  • 684-716: The tests added for the TestClientIP function cover the new scenarios introduced by the changes in handler.go. They include tests for handling X-Forwarded-For headers with IPv6 addresses, multiple IP addresses, and IP addresses with ports. This ensures that the clientIP function is properly tested for the new parsing logic.

Comment on lines +160 to +194
// clientIP returns the client IP address from the request.
//
// If the request passes through a proxy, clientIP parses
// the Forwarded header and the X-Forwarded-For header to
// find the client IP address.
// The clientIP always trusts the values of the Forwarded header
// and the X-Forwarded-For header. Please note
// that if these headers have been altered by an attacker,
// there is a possibility of returning incorrect results.
func clientIP(r *http.Request) (string, bool) {
// Parse Forwarded header.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
forwarded, err := forwardedheader.Parse(r.Header.Values("Forwarded"))
if err == nil && len(forwarded) > 0 {
ip := forwarded[0].For.IP
if ip.IsValid() {
return ip.String(), true
}
}

// Parse X-Forwarded-For header.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
forwardedFor := r.Header.Get("X-Forwarded-For")
if forwardedFor != "" {
if idx := strings.IndexByte(forwardedFor, ','); idx > 0 {
forwardedFor = forwardedFor[:idx]
}
return strings.TrimSpace(forwardedFor), true
forwardedFor = strings.TrimSpace(forwardedFor)

// some proxies may add port number to X-Forwarded-For header.
// e.g. AWS ALB: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html
return getHost(forwardedFor), true
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
return getHost(r.RemoteAddr), false
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The clientIP function has been updated to handle cases where the X-Forwarded-For header includes port numbers. However, there is a potential issue with the getHost function call at line 191. It assumes that the X-Forwarded-For header will contain an IP address followed by a port, but this is not always the case. The getHost function should handle cases where there is no port number present.

Additionally, there is no validation to ensure that the IP address extracted is a valid format before returning it. This could lead to potential security issues if the header is manipulated.

func clientIP(r *http.Request) (string, bool) {
	// Parse Forwarded header.
	forwarded, err := forwardedheader.Parse(r.Header.Values("Forwarded"))
	if err == nil && len(forwarded) > 0 {
		ip := forwarded[0].For.IP
		if ip.IsValid() {
			return ip.String(), true
		}
	}

	// Parse X-Forwarded-For header.
	forwardedFor := r.Header.Get("X-Forwarded-For")
	if forwardedFor != "" {
		if idx := strings.IndexByte(forwardedFor, ','); idx > 0 {
			forwardedFor = forwardedFor[:idx]
		}
		forwardedFor = strings.TrimSpace(forwardedFor)

		// some proxies may add port number to X-Forwarded-For header.
		// e.g. AWS ALB: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html
-		return getHost(forwardedFor), true
+		host, _ := getHost(forwardedFor)
+		if host == "" {
+			return "", false // or handle the error appropriately
+		}
+		return host, true
	}
	return getHost(r.RemoteAddr), false
}

Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
// clientIP returns the client IP address from the request.
//
// If the request passes through a proxy, clientIP parses
// the Forwarded header and the X-Forwarded-For header to
// find the client IP address.
// The clientIP always trusts the values of the Forwarded header
// and the X-Forwarded-For header. Please note
// that if these headers have been altered by an attacker,
// there is a possibility of returning incorrect results.
func clientIP(r *http.Request) (string, bool) {
// Parse Forwarded header.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
forwarded, err := forwardedheader.Parse(r.Header.Values("Forwarded"))
if err == nil && len(forwarded) > 0 {
ip := forwarded[0].For.IP
if ip.IsValid() {
return ip.String(), true
}
}
// Parse X-Forwarded-For header.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
forwardedFor := r.Header.Get("X-Forwarded-For")
if forwardedFor != "" {
if idx := strings.IndexByte(forwardedFor, ','); idx > 0 {
forwardedFor = forwardedFor[:idx]
}
return strings.TrimSpace(forwardedFor), true
forwardedFor = strings.TrimSpace(forwardedFor)
// some proxies may add port number to X-Forwarded-For header.
// e.g. AWS ALB: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html
return getHost(forwardedFor), true
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
return getHost(r.RemoteAddr), false
}
// clientIP returns the client IP address from the request.
//
// If the request passes through a proxy, clientIP parses
// the Forwarded header and the X-Forwarded-For header to
// find the client IP address.
// The clientIP always trusts the values of the Forwarded header
// and the X-Forwarded-For header. Please note
// that if these headers have been altered by an attacker,
// there is a possibility of returning incorrect results.
func clientIP(r *http.Request) (string, bool) {
// Parse Forwarded header.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
forwarded, err := forwardedheader.Parse(r.Header.Values("Forwarded"))
if err == nil && len(forwarded) > 0 {
ip := forwarded[0].For.IP
if ip.IsValid() {
return ip.String(), true
}
}
// Parse X-Forwarded-For header.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
forwardedFor := r.Header.Get("X-Forwarded-For")
if forwardedFor != "" {
if idx := strings.IndexByte(forwardedFor, ','); idx > 0 {
forwardedFor = forwardedFor[:idx]
}
forwardedFor = strings.TrimSpace(forwardedFor)
// some proxies may add port number to X-Forwarded-For header.
// e.g. AWS ALB: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html
host, _ := getHost(forwardedFor)
if host == "" {
return "", false // or handle the error appropriately
}
return host, true
}
return getHost(r.RemoteAddr), false
}

@coveralls
Copy link

Coverage Status

coverage: 61.311% (+0.2%) from 61.151%
when pulling 848892a on xff-may-contain-port-number
into 2f1505d on main.

@shogo82148 shogo82148 merged commit c7e7670 into main Jan 16, 2024
38 checks passed
@shogo82148 shogo82148 deleted the xff-may-contain-port-number branch January 16, 2024 16:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants